#include "widget.h"
#include "ui_widget.h"
#include "stdio.h"
#include "crc16_check.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    bConnectFlag = false;
    ui->recvMsg->setReadOnly(true);

    bHexMod = true;
    ui->hexRadioButton->setChecked(true);
    ui->asciiRadioButton_2->setChecked(false);

    serverIP  = new QHostAddress;
    QString ip=ui->svrIP->text();
    serverIP->setAddress(ip);
    tcpSocket = new QTcpSocket(this);
    port = ui->svrPort->text().toShort();
    connect(tcpSocket, SIGNAL(readyRead()),this, SLOT(dataReceived()));
    connect(tcpSocket, SIGNAL(disconnected()),this, SLOT(slotDisconnected()));
    connect(tcpSocket, SIGNAL(connected()),this, SLOT(slotConnected()));

    connect(&m_sendTimer,SIGNAL(timeout()), this  ,SLOT(TimerSendData()));

    ui->DebugLevel->addItem(tr("FATAL"));
    ui->DebugLevel->addItem(tr("ALERT"));
    ui->DebugLevel->addItem(tr("ERROR"));
    ui->DebugLevel->addItem(tr("WARN"));
    ui->DebugLevel->addItem(tr("NOTICE"));
    ui->DebugLevel->addItem(tr("INFO"));
    ui->DebugLevel->addItem(tr("DEBUG"));

    bagId = 0;
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_closeButton_clicked()
{
    this->close();
}

void Widget::on_connectButton_clicked()
{
    if(bConnectFlag)
    {
        tcpSocket->disconnectFromHost();
        ui->connectButton->setText(tr("连接(&T)"));
        ui->svrIP->setEnabled(true);
        ui->svrPort->setEnabled(true);
        bConnectFlag = false;
    }
    else
    {
        QString ip=ui->svrIP->text();
        serverIP->setAddress(ip);
        port = ui->svrPort->text().toShort();
        tcpSocket->connectToHost(*serverIP,port);
        ui->connectButton->setText(tr("断开(&D)"));
        ui->svrIP->setEnabled(false);
        ui->svrPort->setEnabled(false);
        bConnectFlag = true;
    }
}
//数据接收处理
void Widget::dataReceived()
{
    while (tcpSocket->bytesAvailable()>0)
    {
        QByteArray datagram;
        datagram.resize(tcpSocket->bytesAvailable());

        tcpSocket->read(datagram.data(), datagram.size());

        ui->recvMsg->append("****************************");

        if(bHexMod)
            ui->recvMsg->append(datagram.toHex());
        else
            ui->recvMsg->append(datagram.data());
        ui->recvMsg->append("****************************");
        //ui->sendMsg->setText(datagram.toHex());
    }    
}

//发送键处理函数
void Widget::on_sendButton_clicked()
{
    QByteArray datagram;
    datagram.resize(ui->sendMsg->text().toStdString().length());

    memcpy(datagram.data(), ui->sendMsg->text().toStdString().c_str(), ui->sendMsg->text().toStdString().length());

    int ret = 0;
    if ( bHexMod )
    {
        char *sendBuf = new char[datagram.size()/2 + 1];
        memset(sendBuf,'/0',datagram.size()/2 + 1);
        ascii2Hex(&datagram, sendBuf);
        //ret = tcpSocket->write(sendBuf, datagram.size()/2);
        ret = sendData(sendBuf, datagram.size()/2);

        delete sendBuf;
        sendBuf = NULL;
    }
    else
        //ret = tcpSocket->write(datagram.data(), datagram.size());
        ret = sendData(datagram.data(), datagram.size());
    if(ret < 0)
    {
        m_sendTimer.stop();
        ui->checkBox->setChecked(false);

        QMessageBox::information(this,tr("error"),tr("发生失败: 无效连接!"));
    }
}


//检测到断开连接时的槽处理函数
void Widget::slotDisconnected()
{
    //tcpSocket->disconnectFromHost();
    ui->connectButton->setText(tr("连接(&T)"));
    ui->svrIP->setEnabled(true);
    ui->svrPort->setEnabled(true);
    bConnectFlag = false;
    m_sendTimer.stop();
    ui->checkBox->setChecked(false);

    QMessageBox::information(this,tr("error"),tr("连接已断开!"));
}
void Widget::slotConnected()
{
    char tmp = 0x00;
    QByteArray msg = "<start>";
    msg.append("\x06");
    msg+= tmp;
    msg.append("\x01");
    char srcId =ui->srcId->text().toInt();
    msg.append(srcId);
    msg.append("\x01");
    msg+= tmp;
    msg.append("debug");
    msg.append("<end>");
    tcpSocket->write(msg);
}

void Widget::on_pushButton_clicked()
{
    ui->recvMsg->clear();
}

void Widget::on_clearSendBuf_clicked()
{
    ui->sendMsg->clear();
}

void Widget::on_allSelectButton_clicked()
{
    ui->recvMsg->selectAll();
}

void Widget::on_hexRadioButton_clicked()
{
    bHexMod = true;
}

void Widget::on_asciiRadioButton_2_clicked()
{
    bHexMod = false;
}
//ascii转换为hex
int Widget::ascii2Hex(QByteArray *inData, char *outData)
{
    QByteArray::const_iterator itr1;
    int outIndex = 0;
    itr1 = inData->begin();
    char tmpData_h = 0, tmpData_l = 0;
    for( outIndex = 0; outIndex != inData->size()/2; outIndex++)
    {
        if(itr1 != inData->end())
        {
            if(*itr1 <= '9' &&  *itr1 >= '0')
               tmpData_h = *itr1 - 0x30;
            else if(*itr1 <= 'F' &&  *itr1 >= 'A')
               tmpData_h = *itr1 - 'A' + 0xA;
            else if(*itr1 <= 'f' &&  *itr1 >= 'a')
               tmpData_h = *itr1 - 'a' + 0xA;
        }
        itr1++;
        if(itr1 != inData->end())
        {
            if(*itr1 <= '9' &&  *itr1 >= '0')
               tmpData_l = *itr1 - 0x30;
            else if(*itr1 <= 'F' &&  *itr1 >= 'A')
               tmpData_l = *itr1 - 'A' + 0xA;
            else if(*itr1 <= 'f' &&  *itr1 >= 'a')
               tmpData_l = *itr1 - 'a' + 0xA;
        }
        itr1++;
        outData[outIndex] = (tmpData_h << 4) | (tmpData_l & 0x0f);
    }
    return 0;
}
//检测大于F或者f的输入，大于的话就不让输入
void Widget::on_sendMsg_textEdited(const QString &arg1)
{
    QString tmp(arg1);
    QString::const_iterator itr;
    int index = tmp.size();

    if(bHexMod)
    {
        itr = tmp.end() - 1;
        if(((*itr > 'F') && (*itr < 'Z')) || ((*itr > 'f') && (*itr < 'z')))
        {
            tmp.remove(index-1 , 1);
            ui->sendMsg->setText(tmp);
        }
    }
}

void Widget::on_sendMsg_textChanged(const QString &arg1)
{
    if(bHexMod)
    {
        //ui->recvMsg->append(arg1);
    }
}
//protocol package
int Widget::sendData(char *pData, int iLen)
{
    if( iLen == 0 )
    {
        ui->noticeMsg->setText("no data to send");
        return 0;
    }

    if (ui->srcId->text().size() > 2)
    {
        QMessageBox::information(this,tr("error"),tr("源地址是不是有点长了!"));
        return 0;
    }

    ui->noticeMsg->setText("");

    int iSendLen = sizeof(protocolHead_st)+iLen+5;
    protocolHead_st *pstProtoHead = (protocolHead_st*) new char[iSendLen];

    memcpy(pstProtoHead->headFlag, "<start>",7);
    iSendLen -= 12;
    pstProtoHead->len_l = (iSendLen >> 8) & 0xff;
    pstProtoHead->len_h = iSendLen & 0xff;

    QByteArray datagram;
    int index  = 1;
    if (ui->destModule->currentText() == "event")
    {
        index = 0xE1;
    }
    else
    {
        index = ui->destModule->currentIndex()+1;
    }

    datagram.resize(ui->srcId->text().toStdString().length());
    pstProtoHead->destId = index&0xff;

    //datagram.clear();
    memcpy(datagram.data(), ui->srcId->text().toStdString().c_str(), ui->srcId->text().toStdString().length());
    ascii2Hex(&datagram, (char *)&pstProtoHead->srcId);


    memcpy(pstProtoHead->data, pData, iLen);


    memcpy(&pstProtoHead->data[iLen], "<end>", 5);

    iSendLen += 12; //头尾标识的长度
    //qDebug()<<"dest Id: "<<pstProtoHead->destId<<", srcId: "<<pstProtoHead->srcId<<";-"<<ui->srcId->text();
    int iRet = tcpSocket->write((char *)pstProtoHead, iSendLen);

    datagram.resize(iSendLen);
    memcpy(datagram.data(), (char *)pstProtoHead, iSendLen);

    ui->noticeMsg->setText("send data: "+datagram.toHex());

    delete [] pstProtoHead;

    return iRet;
}

void Widget::on_checkBox_clicked()
{

}
void Widget::TimerSendData()
{
    QByteArray datagram;
    datagram.resize(ui->sendMsg->text().toStdString().length());

    memcpy(datagram.data(), ui->sendMsg->text().toStdString().c_str(), ui->sendMsg->text().toStdString().length());

    int ret = 0;
    if ( bHexMod )
    {
        char *sendBuf = new char[datagram.size()/2 + 1];
        memset(sendBuf,'/0',datagram.size()/2 + 1);
        ascii2Hex(&datagram, sendBuf);
        //ret = tcpSocket->write(sendBuf, datagram.size()/2);
        ret = sendData(sendBuf, datagram.size()/2);

        delete sendBuf;
        sendBuf = NULL;
    }
    else
        //ret = tcpSocket->write(datagram.data(), datagram.size());
        ret = sendData(datagram.data(), datagram.size());
    if(ret < 0)
    {
        QMessageBox::information(this,tr("error"),tr("发生失败: 无效连接!"));
    }
}

void Widget::on_checkBox_clicked(bool checked)
{
    if( checked )
    {
        int itervalTime = ui->IntervalTime->text().toInt();
        m_sendTimer.setInterval(itervalTime);
        m_sendTimer.start();
        ui->noticeMsg->setText("开始定时发送");
    }
    else
    {
        m_sendTimer.stop();
        ui->noticeMsg->setText("停止定时发送");
    }
}

void Widget::on_setDebugLevel_clicked()
{
    int index = ui->DebugLevel->currentIndex();

    QByteArray datagram;
    datagram.resize(6);

    char buff[6] = {0x14, 0x00, 0x00, 0x00,0x00,0x00};
    buff[2] = index & 0xff;

    memcpy(datagram.data(), buff, 6);

    int ret = 0;
    if ( bHexMod )
    {
        ret = sendData(datagram.data(), datagram.size());
    }

    if(ret < 0)
    {
        QMessageBox::information(this,tr("error"),tr("发生失败: 无效连接!"));
    }
}
